package bluecove;

import config.ConsoleUtil;

import javax.obex.ClientSession;
import javax.obex.HeaderSet;
import javax.obex.Operation;
import javax.microedition.io.Connector;
import java.util.Map;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Class description...
 *
 * @author mvu
 */
public class DeviceImpl implements Device{
  private static String SERVICE_URL = "btgoep://001813107B02:7;authenticate=false;encrypt=false;master=false";
  public static String DEFAULT_PATH = "Phone memory/Other";
  
  public void receive(Map<String, String> files) throws IOException {
    ClientSession conn = (ClientSession) Connector.open(SERVICE_URL);
    setHeaderToFolderBrowsing(conn);
    goToPath(DEFAULT_PATH, conn);

    for(Map.Entry<String,String> entry : files.entrySet()){
      sendFile(entry.getKey() + ".html", entry.getValue(), conn);
    }

    conn.disconnect(conn.createHeaderSet());
    conn.close();
  }

  private void setHeaderToFolderBrowsing(ClientSession conn) throws IOException {
    //Target Header must be set to the Folder Browsing UUID:
    //F9EC7BC4-953C-11D2-984E-525400DC9E09.
    byte[] FBUiid = {(byte) 0xF9, (byte) 0xEC, (byte) 0x7B, (byte) 0xC4, (byte) 0x95, (byte) 0x3C, (byte) 0x11, (byte) 0xD2,
            (byte) 0x98, (byte) 0x4E, (byte) 0x52, (byte) 0x54, (byte) 0x00, (byte) 0xDC, (byte) 0x9E, (byte) 0x09};
    //Connect
    HeaderSet header = conn.createHeaderSet();
    header.setHeader(HeaderSet.TARGET, FBUiid);
    conn.connect(header);
  }

  private void goToPath(String path, ClientSession conn) throws IOException {
    HeaderSet header;
    String[] folders = path.split("/");
    //Go the desired folder
    for (String folder : folders) {
      header = conn.createHeaderSet();
      header.setHeader(HeaderSet.NAME, folder);
      conn.setPath(header, false, false);
    }
  }

  private void sendFile(String fileName, String text, ClientSession conn) throws IOException {
    ConsoleUtil.debug("Sending " + fileName);
    HeaderSet header;
    // delete file on device
    header = conn.createHeaderSet();
    header.setHeader(HeaderSet.NAME, fileName);
    conn.delete(header);

    // copy new file to device
    header = conn.createHeaderSet();
    header.setHeader(HeaderSet.NAME, fileName);
    Operation op = conn.put(header);
    OutputStream os = op.openOutputStream();
    byte[] b = text.getBytes();
    int r = b.length;
    os.write(b, 0, r);
    os.close();
    op.close();
    ConsoleUtil.debug("Done");
  }
}
